package leesoft.configuration.core;

import java.io.Writer;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import leesoft.configuration.databeans.FieldMap;
import leesoft.configuration.databeans.Integration;
import leesoft.configuration.databeans.Plugin;
import leesoft.configuration.interfaces.AfterPlugin;
import leesoft.configuration.interfaces.IRecordSetMapHandler;
import leesoft.configuration.xmlconfig.Configuration;

import org.apache.commons.dbutils.ResultSetHandler;

public class RowHandler implements IRecordSetMapHandler {
	Integration intg;
	Writer writer;;
	
	public RowHandler(Integration intg,Writer writer){
		this.intg=intg;
		this.writer=writer;
	}
	@Override
	public boolean handle(Map rowMap) {
		try{
			intg.afterPluginExecute(rowMap);
			String targetTable=intg.getTargetTable();
			List<FieldMap> fieldMapList=intg.getFieldMapList();
			StringBuffer sqlout=new StringBuffer("insert into "+targetTable+"(");
			String op="";
			for(FieldMap f:fieldMapList){
				sqlout.append(op).append(f.getTarget());
				op=",";
			}
			sqlout.append(")values(");
			op="";
			for(FieldMap f:fieldMapList){
				sqlout.append(op).append(getSqlValue(rowMap,f.getSource()));
				op=",";
			}
			sqlout.append(")");

			writer.write(sqlout.toString()+";\n");
			writer.flush();
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}	
	}
	public String getSqlValue(Map rowMap,String fieldName) throws Exception{
		if(!rowMap.containsKey(fieldName.toLowerCase())){
			System.out.println("key:"+fieldName+" doesn't exist in the result set");
			throw new Exception("key "+fieldName+" not found in the result set!");
		}
		Object value=rowMap.get(fieldName.toLowerCase());
		if(value==null)
			return "NULL";
		else{
			return "'"+value.toString().replaceAll("'", "''")+"'";
		}
		
	}
	

}
